<template>
	<PageContainer name="反馈与建议" :show-footer="true">
		<view class="title">反馈内容</view>
		<textarea v-model="contents" :maxlength="2000" :auto-height="true" placeholder="请输入反馈的问题..."></textarea>
		<view class="upload-file">
			<view class="title">上传图片</view>
			<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :maxCount="5">
			</u-upload>
		</view>
		<template #footer>
			<view class="global-page-footer flex-row">
				<button class="global-submit-button" @click="submit">提 交</button>
			</view>
		</template>
	</PageContainer>
</template>

<script>
	import PageContainer from '@/components/PageContainer/PageContainer.vue';
	import {
		saveFeedback,
		uploadFeedbackFile,
	} from '@/api/other/feedback.js';
	import {
		getToken
	} from '@/utils/auth';
	export default {
		components: {
			PageContainer
		},
		data() {
			return {
				contents: '',
				fileList: [],
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1);
			},
			// 上传图片
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this['fileList'].length
				lists.map((item) => {
					this['fileList'].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this['fileList'][fileListLen]
					this['fileList'].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.data
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: uploadFeedbackFile(),
						filePath: url,
						name: 'file',
						header: {
							['Authorization']: 'Bearer ' + getToken(),
							['entfrm']: getToken(),
						},
						success: result => {
							resolve(JSON.parse(result.data))
						}
					});
				})
			},
			async submit() {
				const imgPaths = this.fileList.map(item => item.url).join(",");
				const contents = this.contents;
				await saveFeedback({
					imgPaths,
					contents,
				})
				uni.showToast({
					icon: 'none',
					title: '提交成功',
				})
				setTimeout(() => {
					uni.navigateBack();
				}, 500)
			}
		}
	}
</script>

<style scoped lang="scss">
	.title {
		font-size: 32rpx;
		margin-top: 36rpx;
		margin-bottom: 28rpx;
	}

	textarea {
		padding: 18rpx 30rpx;
		width: 100%;
		min-height: 420rpx;
		background-color: #f6f6f6;
		box-sizing: border-box;
	}

	.upload-file {
		margin-top: 60rpx;
	}
</style>